<template>

  <el-row :gutter="20">
    <el-col :span="12">
      <el-card shadow="never" class="border-0">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
          <el-form-item label="认证状态：">

            <div v-if="store.state.user.is_auth == 0">
              <el-tag type="warning">待认证</el-tag>
            </div>
            <div v-if="store.state.user.is_auth == 1">
              <el-tag type="success">认证成功</el-tag>
            </div>
            <div v-if="store.state.user.is_auth == 2">
              <el-tag type="danger">未认证成功</el-tag>
              <span style="margin-left: 10px;color: #e96363;">{{ store.state.user.back_reason }}</span>
            </div>
            <div v-if="store.state.user.is_auth == 3">
              <el-tag type="warning">待审核</el-tag>
            </div>

          </el-form-item>

          <el-form-item label="当前身份" v-if="store.state.user.is_auth == 1">
            <div v-if="store.state.user.is_auth == 1">
              <el-tag v-if="form.type == 0">普通用户</el-tag>
              <el-tag v-if="form.type == 1">企业管理员</el-tag>
              <el-tag v-if="form.type == 2">企业员工</el-tag>
              <el-tag v-if="form.type == 10">超级管理员</el-tag>
            </div>
          </el-form-item>

          <el-form-item label="绑定套餐：">
            <el-check-tag v-if="skuUser">{{ skuUser.title }}</el-check-tag>
            <el-check-tag v-else @click="bindtaocan">未绑定</el-check-tag>

            <span v-if="skuUser">剩余 <span style="color:#338be9;">{{ skuUser.balance_times }}</span> 次 </span>
            <!-- <span style="margin-left: 20px;color:#338be9;">续费</span> -->
          </el-form-item>

          <el-form-item v-if="company && store.state.user.group_id == 2" label="公司名称：">
            <el-input v-model="company.name" :disabled="store.state.user.group_id == 2?false:true" />
          </el-form-item>
          <el-form-item v-if="company && store.state.user.group_id == 2" label="公司法人：">
            <el-input v-model="company.corporation" :disabled="store.state.user.group_id == 2?false:true" />
          </el-form-item>
          <el-form-item v-if="company && store.state.user.group_id == 2" label="法人手机号：">
            <el-input v-model="company.mobile" :disabled="store.state.user.group_id == 2?false:true" />
          </el-form-item>
          <el-form-item v-if="company && store.state.user.group_id == 2" label="法人身份证：">
            <el-input v-model="company.id_card" :disabled="store.state.user.group_id == 2?false:true" />
          </el-form-item>

          <el-form-item label="用户名：">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="姓名：">
            <el-input v-model="form.first_name" />
          </el-form-item>
          <el-form-item label="昵称：">
            <el-input v-model="form.nickname" />
          </el-form-item>
          <el-form-item label="手机号：">
            <el-input v-model="form.mobile" />
          </el-form-item>
          <el-form-item label="身份证号：">
            <el-input v-model="form.id_card" />
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card shadow="never" class="border-0">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">

          <el-form-item v-if="company && store.state.user.group_id == 2" label="法人身份证">
            <div class="demo-image">
              <div class="block">
                <el-image style="width: 200px; height: 100px" :src="company.corporation_front_url" />
              </div>
              <div class="block">
                <el-image style="width: 200px; height: 100px" :src="company.corporation_back_url" />
              </div>
            </div>
          </el-form-item>
          <el-form-item v-if="company && store.state.user.group_id == 2" label="营业执照">
            <div class="demo-image">
              <div class="block">
                <el-image style="width: 200px; height: 100px" :src="company.license_url" />
              </div>
            </div>
          </el-form-item>



          <el-form-item label="用户身份证照片">
            <el-col :span="11">
              <UploadFile style="width: 200px;"
                :data="{ img_url: form.id_card_front_url, image_show_url: image_id_card_front_url }"
                @success="handleCardFrontUploadSuccess" />
            </el-col>

            <el-col :span="11">
              <UploadFile style="width: 200px;"
                :data="{ img_url: form.id_card_back_url, image_show_url: image_id_card_back_url }"
                @success="handleCardBackUploadSuccess" />
            </el-col>


          </el-form-item>

          <!-- <el-form-item label="头像">
        <UploadFile style="width: 200px;"
          :data="{ img_url: form.id_card_back_url, image_show_url: form.id_card_back_url }"
          @success="handleCardBackUploadSuccess" />
      </el-form-item> -->

          <!-- <el-form-item label="身份证">

        <div class="demo-image">
          <div class="block">
            <el-image style="width: 200px; height: 100px" :src="form.id_card_front_url" />
          </div>
          <div class="block">
            <el-image style="width: 200px; height: 100px" :src="form.id_card_back_url" />
          </div>
        </div>
      </el-form-item> -->

          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>


  <el-dialog v-model="dialogVisible" title="详情" width="70%" height="80%" :before-close="handleClose">
    <el-form :model="form" label-width="120px">
      <el-form-item label="套餐" prop="skus_id">
        <el-select v-model="form.title" placeholder="选择套餐" @change="changeSku" clearable filterable style="width: 100%">
          <el-option v-for="item in skusList" :key="item.id" :label="item.title" :value="item">
          </el-option>
        </el-select>

      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">返回</el-button>
        <el-button type="primary" @click="bindSkuUser(form.id)">绑定</el-button>
        <!-- <el-popconfirm title="是否绑定该套餐？" confirmButtonText="确认" cancelButtonText="取消"
          @confirm="bindSkuUser(form.id)">
          <template #reference>
            <el-button type="primary">绑定</el-button>
          </template>
</el-popconfirm> -->
      </span>
    </template>

  </el-dialog>
</template>
<script setup>
// vue 内部方法
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

// 页面组件
import ListHeader from "~/components/ListHeader.vue"
import FormDrawer from "~/components/FormDrawer.vue"
import SearchForm from "~/components/SearchForm.vue"
import SearchItem from "~/components/SearchItem.vue"
import UploadFile from "~/components/UploadFile.vue"
import { Search } from '@element-plus/icons-vue'

// 公共方法
import { useInitTable, useInitForm } from "~/composables/useCommon"
import { goTo, showMessage } from "~/composables/util"
import { httpUrl } from "~/config"
import { toast } from '~/composables/util'

// api
import {
  getUserList,
  getUserInfo,
  setUserInfo,
  putUser,
} from "~/api/user/index"
import { getSkusBindList, getSkusList, postSkusBind, putSkusBind, deleteSkus, patchSkusStatus } from "~/api/platefrom/skus";

import {
  getCompanyList,
  postCompany,
  putCompany,
  deleteCompany,
  setCompanyAuth,
} from "~/api/company/index"


// 路由管理
const router = useRouter()

// 设置用户认证
const store = useStore()
const setUserAuth = async (id, is_auth) => {
  await setUserInfo({ id: id, is_auth: is_auth }).then((res) => {
    store.dispatch("getUserInfo").then(() => getList())
  })
}

// 套餐信息
const skuUser = ref()
const company = ref()
onMounted(() => {
  getSkusBindList({ user_id: store.state.user.id }).then((res) => {
    if (res.data.results.length > 0) {
      skuUser.value = res.data.results[0]
    }

  })
  if (store.state.user.company_id) {
    getCompanyList({ company_id: store.state.user.company_id }).then((res) => {
      if (res.data.results.length > 0) {
        company.value = res.data.results[0]
        if (!company.value.corporation_front_url.includes(httpUrl)) {
          company.value.corporation_front_url = httpUrl + company.value.corporation_front_url
          company.value.corporation_back_url = httpUrl + company.value.corporation_back_url
          company.value.license_url = httpUrl + company.value.license_url
        }

      }
    })
  }


})


// 修改个人信息
const form = ref({})
form.value = store.state.user
const image_id_card_front_url = ref('')
const image_id_card_back_url = ref('')
image_id_card_front_url.value = httpUrl + form.value.id_card_back_url
image_id_card_back_url.value = httpUrl + form.value.id_card_front_url

// 身份证正面上传成功
const handleCardFrontUploadSuccess = (res) => {
  form.id_card_front_url = res.response.url;
  form.id_card_front_image_id = res.response.id;
  image_id_card_front_url.value = res.response.url;
}

// 身份证反面上传成功
const handleCardBackUploadSuccess = (res) => {
  form.id_card_back_url = res.response.url;
  form.id_card_back_image_id = res.response.id;
  image_id_card_back_url.value = res.response.url;
}

// 详情
const detail = ref({})
const dialogVisible = ref(false)
// 绑定套餐
const skusList = ref([])
const bindtaocan = (row) => {
  if (store.state.user.is_auth == '2' || store.state.user.is_auth == '3') {
    showMessage('未认证成功,不能绑定套餐', 'warning')
    return false
  }

  dialogVisible.value = true
  // 获取套餐信息
  getSkusList({}).then((res) => {
    skusList.value = res.data
  })
};
// 选择套餐
const changeSku = (res) => {
  form.value.skus_id = res.id
  form.value.title = res.title
}

const bindSkuUser = (user_id) => {
  console.log(form.value)
  if (form.value.type == '0') {
    let data = {
      user_id: user_id,
      skus_id: form.value.skus_id,
      title: form.value.title
    }
    postSkusBind(data).then((res) => {
      dialogVisible.value = false
      putUser({ id: id, skus_id: skus_id }).then((res) => {
        store.dispatch("getUserInfo").then(() => getList())
      })
      showMessage(res.msg, 'success')
    })

  }
  if (form.value.type == '1' || form.value.type == '2') {

    let data = {
      user_id: user_id,
      skus_id: form.value.skus_id,
      title: form.value.title,
      company_name: form.value.company_name,
      company_id: form.value.company_id
    }
    postSkusBind(data).then((res) => {
      dialogVisible.value = false
      showMessage(res.msg, 'success')
    })
  }

}

// 手机号验证
const checkPhone = (rule, value, callback) => {
  // 手机号验证
  if (!value) {
    return callback(new Error("手机号不能为空"));
  } else {
    const reg = /^1[3456789]\d{9}$/;
    if (reg.test(value)) {
      callback();
    } else {
      return callback(new Error("请输入正确的手机号"));
    }
  }
}

// 身份证验证
const isCardId = (rule, value, callback) => {
  if (value) {
    const reg =
      /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
    const card = reg.test(value);
    if (!card) {
      callback(new Error("身份证号格式有误！"));
    } else {
      callback();
    }
  } else {
    callback();
  }
  callback();
}

// 表单提交
const rules = ref({
  first_name: [
    {
      required: true,
      message: "姓名不能为空",
      trigger: "blur",
    },
  ],

  mobile: [
    { required: true, message: "请输入正确手机号", trigger: "blur" },
    { validator: checkPhone, trigger: ["blur", "change"] },
  ],
  id_card: [
    { required: true, message: "请输入正确身份证号", trigger: "blur" },
    { validator: isCardId, trigger: ["blur", "change"] },
  ],
  id_card_front_url: [
    { required: true, message: "请上传图片", trigger: "blur" },
  ],
  id_card_back_url: [
    { required: true, message: "请上传图片", trigger: "blur" },
  ],
})

// 表单验证
// 提交
const formRef = ref(null)
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) return;

    form.username = store.state.user.username

    form.company_id = store.state.user.company_id

    form.user_id = store.state.user.id

    if (store.state.user.is_auth == '1') {
      form.value.is_auth = 1
    } else {
      form.value.is_auth = '3'
    }

    putUser(form.user_id, form.value).then((res) => {
      if (store.state.user.is_auth == '1') {
        toast("提交成功!");
      } else {
        showMessage("提交成功!等待管理员审核!");
      }

    })
      .finally(() => {
        if (store.state.user.is_auth == '1') {
          toast("提交成功!");
        } else {
          router.go(0)
        }

      });
  })
}

</script>

<style scoped>
.el-input-group__append:first-child {
  margin: 0 0px !important;
}

.demo-image {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>